/**
 * 
 */
package edu.uwm.nlp.jude.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import edu.uwm.nlp.jude.internal.DocumentHandlerException;
import edu.uwm.nlp.jude.internal.FileProcessor;

/**
 * @author qing
 *
 * Jul 24, 2009
 */
public class FileUtil {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length != 2)
			System.out.println("convert pdf to text\n--pdfs --saveDir");
		else
			pdfsToTexts(args[0], args[1]);
	}
	
	
	public static void pdfsToTexts(String pdfs, String saveDir)
	{
		FileProcessor processor = new FileProcessor();
		File pdfDir = new File(pdfs);
		File[] pdfFiles = pdfDir.listFiles();
		FileWriter writer = null;
		for(int i=0; i<pdfFiles.length; i++)
		{
			try {
				System.out.println("processing ["+i+"]"+pdfFiles[i].getName());
				String text = processor.getDocumentText(pdfFiles[i].getAbsolutePath());
				writer = new FileWriter(saveDir+getFileName(pdfFiles[i].getName(),".pdf", ".txt"));
				writer.append(text);
				writer.close();
			} catch (DocumentHandlerException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("Finish. save="+saveDir+"\npdfs="+pdfs);
		
	}
	
	public static String getFileName(String fullName, String ext, String newExt)
	{
		String fileName = fullName;
		int end = fullName.lastIndexOf(ext);
		if(end != -1)
			fileName = fullName.substring(0, end);
		if(newExt != null)
			fileName += newExt;
		return fileName;
	}

}
